<template>
  <div>
    <div
      v-if="searchStatus"
      :class="!props.searchStatus ? '' : 'box-shadow pad10 mgb10'"
    >
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="名称">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="queryParams.Remark"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
          </div>
          <div class="flex fnw acenter jend">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <MyTable
      :tableList="tableList"
      :total="Total"
      v-model:selectList="myselectList"
      :columns="columns"
      v-model:page="page"
      ref="tableRef"
      v-model:searchStatus="searchStatus"
      :btnList="$checkBtn(props.Permise.tab)"
      @getList="getList"
      @edit="handleEdit"
      @delete="handleDelete"
    >
      <template v-slot:tabTop>
        <el-button
          type="primary"
          v-hasPermi="props.Permise.add"
          icon="CirclePlusFilled"
          @click="handleAdd"
          >添加{{ props.Label }}方案</el-button
        >
        <el-button
          v-if="props.showSet"
          type="primary"
          v-hasPermi="props.Permise.add"
          @click="filterRouter"
          >{{ props.Label }}项配置</el-button
        >
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      :title="title"
      :formRef="formRef"
      :width="1000"
      @confirm="confirm"
    >
      <el-form :model="formData" :rules="rules" inline ref="formRef">
        <el-row class="fw100">
          <el-form-item label="方案编号" prop="Code">
            <el-input v-model="formData.Code" placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="方案名称" prop="Name">
            <el-input v-model="formData.Name" placeholder="请输入" clearable />
          </el-form-item>
        </el-row>

        <el-row>
          <el-form-item
            label="备注"
            prop="Remark"
            label-width="77px"
            class="w100"
          >
            <el-input
              v-model="formData.Remark"
              type="textarea"
              placeholder="请输入"
              clearable
            />
          </el-form-item>
        </el-row>
      </el-form>
      <MyTable
        v-model:tableList="showSelectList"
        :total="selectTotal"
        :columns="selectColumns"
        :btnList="['delete']"
        v-model:page="selectPage"
        :toolbar="false"
        :searchStatus="false"
        @delete="selectDelete"
        height="500"
      >
        <template v-slot:tabTop>
          <el-button
            type="primary"
            @click="bindExecution(`选择${props.Label}项`)"
            >选择{{ props.Label }}项</el-button
          >
        </template>
      </MyTable>
    </MyDialog>
    <MyDialog
      v-model:show="bindDialog"
      :title="bindTitle"
      @confirm="subConfirm"
      :destroy="true"
    >
      <ItemList
        :searchStatus="false"
        :Type="props.Type"
        :Label="props.Label"
        v-model:selectList="selectList"
      ></ItemList>
    </MyDialog>
  </div>
</template>

<script setup name="TeachMaintainPaln">
import { ref, getCurrentInstance, onMounted } from "vue";
import ItemList from "@/views/teachingDevice/TeachMaintainPaln/itemList";
import {
  GetMaintainPlanList_Page,
  AddMaintainPlan,
  EditMaintainPlan,
  DelMaintainPlan,
  GetMaintainPlanDetail,
} from "@/api/teachDevice/maintain.js";
import { useRouter } from "vue-router";
const emit = defineEmits(["update:selectList"]);
const router = useRouter();
const props = defineProps({
  Type: {
    default: 1,
  },
  Label: {
    default: "保养",
  },
  searchStatus: {
    default: true,
  },
  selectList: {
    default: [],
  },
  showSet: {
    default: true,
  },
  Permise: {
    default: {
      tab: ["TeachMaintainPaln:delete", "TeachMaintainPaln:edit"],
      add: ["TeachMaintainPaln:add"],
    },
  },
});

const { proxy } = getCurrentInstance();
const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: "序号" },
  { label: "编号", prop: "Code" },
  { label: "名称", prop: "Name" },
  //   { label: "类型", prop: "TypeName" },
  { label: "备注", prop: "Remark" },
  { label: "创建时间", prop: "CreateTime" },
  { label: "创建人", prop: "CreateUser", user: true },
  { label: "修改时间", prop: "UpdateTime" },
  { label: "修改人", prop: "UpdateUser", user: true },
  { label: "操作", width: 160 },
]);
if (!props.searchStatus) {
  columns.value.unshift({
    label: "多选框",
  });
}
const tableRef = ref();
const selectColumns = ref([
  { label: "序号" },
  { label: "编号", prop: "Code", width: 160 },
  { label: "内容", prop: "Content" },
  { label: "排序", prop: "Sort", inputNum: true, width: 180 },
  { label: "操作", width: 100 },
]);

proxy.$formatKey(columns.value);
proxy.$formatKey(selectColumns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10,
});
const selectPage = ref({
  PageIndex: 1,
  PageSize: 10,
});
const searchStatus = ref(true);
searchStatus.value = props.searchStatus;
const queryParams = ref({
  Code: "",
  Name: "",
  NoPage: "", //如果传"true"，则返回全部数据不分页
});
const queryRef = ref();
const show = ref(false);
const title = ref();
const formRef = ref();
const rules = ref({
  Code: [{ required: true, message: "请输入", trigger: "blur" }],
  Name: [{ required: true, message: "请输入", trigger: "blur" }],
  //   Type: [{ required: true, message: "请选择", trigger: "change" }],
});
const formData = ref({});
const selectList = ref([]);
const bindDialog = ref(false);
const bindTitle = ref("");
const selectTotal = ref(0);
const showSelectList = ref([]);
const origonList = ref([]);
onMounted(() => {
  origonList.value = props.selectList;
  getList();
});
const Types = {
  1: "装备",
  2: "工具",
};
async function getList() {
  try {
    show.value = false;
    let query = {
      ...queryParams.value,
      ...page.value,
      Type: props.Type,
    };
    let res = await GetMaintainPlanList_Page(query);
    // res.data.List?.forEach((item) => {
    //   item.TypeName = Types[item.Type];
    // });
    tableList.value = res.data.List;
    Total.value = res.data.Total;
    selectList.value = tableList.Items;
    validateRow();
  } catch (error) {
    console.log(error);
  }
}

function validateRow() {
  tableList.value?.map((item) => {
    props.selectList?.map((item2) => {
      if (item.ID == item2.ID) {
        item.Interval = item2.Interval;
        item.LastMaintainTime = item2.LastMaintainTime;
        item.Remark = item2.Remark;
        item.Principal = item2.Principal;
        item.Type = item2.Type;
        tableRef.value.tabRef.toggleRowSelection(item, true);
      }
    });
  });
}
const myselectList = computed({
  get: () => props.selectList,
  set: (n) => {
    origonList.value = origonList.value?.filter((item) => {
      let bool = n?.some((item2) => {
        return item2.ID == item.ID;
      });
      return !bool;
    });

    let list = [...origonList.value, ...n];
    console.log(list);
    emit("update:selectList", list);
  },
});

function bindExecution(title) {
  bindTitle.value = title;
  bindDialog.value = true;
}

async function confirm(val) {
  try {
    if (val) {
      let query = {
        ...formData.value,
        Items: showSelectList.value?.map((item) => {
          return {
            ID_Items: item.ID, //执行项ID
            Sort: item.Sort, //排序
          };
        }),
        Type: props.Type,
      };
      if (formData.value.ID) {
        await EditMaintainPlan(query);
        proxy.$modal.msgSuccess("修改成功");
      } else {
        await AddMaintainPlan(query);
        proxy.$modal.msgSuccess("添加成功");
      }

      getList();
    }
  } catch (error) {
    console.log(error);
  }
}

function filterRouter() {
  switch (props.Type) {
    case 1:
      router.push({
        path: "/TeachMaintainPalnItem",
        query: { Type: props.Type, Label: props.Label },
      });
      break;
    case 2:
      router.push({
        path: "/OfficeInspectPlanItem",
        query: { Type: props.Type, Label: props.Label },
      });
      break;
  }
}

function subConfirm() {
  // selectTotal.value = selectList.value.length;
  showSelectList.value = selectList.value;
  bindDialog.value = false;
}

function selectDelete(row) {
  selectList.value = selectList.value?.filter((item) => item.ID != row.ID);
  showSelectList.value = showSelectList.value?.filter(
    (item) => item.ID != row.ID
  );
}

async function handleEdit(row) {
  try {
    let { data } = await GetMaintainPlanDetail({ ID: row.ID });
    formData.value = {
      Code: data.Info.Code,
      Name: data.Info.Name,
      Remark: data.Info.Remark,
      ID: data.Info.ID,
      Type: props.Type,
    };
    data.Items?.forEach((item) => {
      item.ID = item.ID_Items;
    });
    showSelectList.value = data.Items;
    selectList.value = showSelectList.value;
    title.value = `修改${props.Label}方案`;
    show.value = true;
  } catch (error) {
    console.log(error);
  }
}
async function handleDelete(row) {
  try {
    await DelMaintainPlan({ ID: row.ID });
    proxy.$modal.msgSuccess("删除成功");
    getList();
  } catch (error) {
    console.log(error);
  }
}
function handleAdd() {
  formData.value = {};
  showSelectList.value = [];
  selectList.value = [];
  title.value = `添加${props.Label}方案`;
  show.value = true;
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: "",
    Name: "",
    NoPage: "",
  };
  handleQuery();
}
</script>

<style lang="scss" scoped>
.selectBox {
  display: flex;
  border: 1px solid #ddd;
  margin-bottom: 10px;
  .selectItem {
    padding: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
